package com.example.demo.study.effectivejava.annotation;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

// Program containing marker annotations
public class Sample {
    @MyTest
    public static void m1() {
    }  // Test should pass

    public static void m2() {
    }

    @MyTest
    public static void m3() {     // Test should fail
        throw new RuntimeException("Boom");
    }

    public static void m4() {
    }

    @MyTest
    public void m5() {
    } // INVALID USE: nonstatic method

    public static void m6() {
    }

    @MyTest
    public static void m7() {    // Test should fail
        throw new RuntimeException("Crash");
    }

    public static void m8() {
    }


    public static void main(String[] args) throws Exception {
        int tests = 0;
        int passed = 0;
        Class<?> testClass = Class.forName("com.example.demo.study.effectivejava.annotation.Sample");
        for (Method m : testClass.getDeclaredMethods()) {
            if (m.isAnnotationPresent(MyTest.class)) {
                tests++;
                try {
                    m.invoke(null);
                    passed++;
                } catch (InvocationTargetException wrappedExc) {
                    Throwable exc = wrappedExc.getCause();
                    System.out.println(m + " failed: " + exc);
                } catch (Exception exc) {
                    System.out.println("Invalid @Test: " + m);
                }
            }
        }
        System.out.printf("Passed: %d, Failed: %d%n",
                passed, tests - passed);
    }
}
